package com.tomorrow.simplefactory.http;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URL;

import com.tomorrow.weather.mInterface.HttpApi;

import android.util.Log;

/**
 * 
 * @title
 * @description
 * @author Mike
 * @company www.tomorrow.com
 * @version 1.0
 * @created 2012-10-20
 * 
 */
public class HttpUtils implements HttpApi
{

	private static final String DEBUG_TAG = "HttpUtils";
	private static HttpUtils httpUtils = null;

	private HttpUtils()
	{

	}

	public static HttpUtils get()
	{
		if (httpUtils == null)
		{
			httpUtils = new HttpUtils();
		}
		return httpUtils;
	}

	@Override
	public String getUrlContent(String strUrl)
	{
		InputStream is = null;
		int len = 5024;
		try
		{
			URL url = new URL(strUrl);
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			connection.setReadTimeout(5000);
			connection.setConnectTimeout(10000);
			connection.setRequestMethod("GET");
			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.connect();
			int response = connection.getResponseCode();
			Log.d(DEBUG_TAG, "The response is : " + response);
			if (response == 200)
			{
				is = connection.getInputStream();
				//len = connection.getContentLength();
				String contentAsString = readInputStream(is, len);
				return contentAsString;
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			if (is != null)
			{
				try
				{
					is.close();
				}
				catch (IOException e)
				{
					e.printStackTrace();
				}
			}
		}
		return null;
	}

	private String readInputStream(InputStream stream, int len)
			throws IOException
	{
		Reader reader = null;
		reader = new InputStreamReader(stream, "UTF-8");
		char[] buffer = new char[len];
		reader.read(buffer);
		return new String(buffer);
	}

}
